package service

import (
	"net/http"
	"prim-server/logger"

	"github.com/gorilla/websocket"
)

func checkOrigin(r *http.Request) bool {
	return true
}

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin:     checkOrigin,
}

// 判断是否为websocket链接
func IsWebSocket(r *http.Request) bool {
	if websocket.IsWebSocketUpgrade(r) {
		return true
	}
	return false
}

// 构建websocket链接
func BuildWebSocket(w http.ResponseWriter, r *http.Request) (*websocket.Conn, error) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		logger.Error(err.Error())
		return nil, err
	}
	return conn, nil
}

func ReadMessageFromWebSocket(conn *websocket.Conn) (int, []byte, error) {
	msgType, msg, err := conn.ReadMessage()
	if err != nil {
		if IsWebSocketClosed(msgType, err) {
			logger.Warn(err.Error())
		} else {
			logger.Error(err.Error())
		}
		return msgType, nil, err
	}
	return msgType, msg, nil
}

func WriteMessageIntoWebSocket(message []byte, conn *websocket.Conn) error {
	if err := conn.WriteMessage(websocket.TextMessage, message); err != nil {
		logger.Error(err.Error())
		return err
	}
	return nil
}

func IsWebSocketClosed(msgType int, err error) bool {
	if msgType == websocket.CloseMessage || websocket.IsCloseError(err, websocket.CloseAbnormalClosure, websocket.CloseGoingAway) {
		return true
	}
	return false
}
